package com.example.audiostreaming.activity;

import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.viewpager.widget.ViewPager;

import com.example.audiostreaming.R;
import com.example.audiostreaming.adapters.AdapterPlayerTrackViewPager;
import com.example.audiostreaming.base.BaseActivity;
import com.example.audiostreaming.implement.ImplPlayerLogic;
import com.example.audiostreaming.interfaces.IPlayerViewCallback;
import com.example.audiostreaming.utils.UtilLog;
import com.example.audiostreaming.views.ViewPopWindow;
import com.ximalaya.ting.android.opensdk.model.track.Track;
import com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl.PlayMode.PLAY_MODEL_LIST_LOOP;
import static com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl.PlayMode.PLAY_MODEL_RANDOM;
import static com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl.PlayMode.PLAY_MODEL_SINGLE_LOOP;

/**
 * 播放界面
 */
public class PlayerActivity extends BaseActivity {
    private static final String TAG = "PlayerActivity";

    private ImageView mPlayOrPauseBtn;
    private ImplPlayerLogic mInstanceImplPlayerLogic;
    private PlayerViewCallback mPlayerViewCallback;
    private SimpleDateFormat mMinFormat = new SimpleDateFormat("mm:ss");
    private SimpleDateFormat mHourFormat = new SimpleDateFormat("hh:mm:ss");
    private TextView mDurationTime;
    private TextView mCurrPosTime;
    private SeekBar mDurationSeekBar;
    private int mCurrentPragress = 0;
    private boolean mIsUserTouchProgressBar = false;
    private ImageView mPlayPreBtn;
    private ImageView mPlayNextBtn;
    private TextView mTrackTitle;
    private String mTrackTitleText;
    private ViewPager mTrackViewPager;
    private AdapterPlayerTrackViewPager mAdapterPlayerTrackViewPager;
    private boolean mIsUserSlidePager = false;
    private ImageView mPlayerListBtn;
    private ImageView mPlayModeSwitchBtn;
    private XmPlayListControl.PlayMode mCurrentMode = XmPlayListControl.PlayMode.PLAY_MODEL_LIST_LOOP;
    private static Map<XmPlayListControl.PlayMode, XmPlayListControl.PlayMode> sPlayModeRule = new HashMap<>();
    //处理播放模式的切换
    //列表循环：PLAY_MODEL_LIST_LOOP
    //随机播放：PLAY_MODEL_RANDOM
    //单曲循环：PLAY_MODEL_SINGLE_LOOP

    static {
        sPlayModeRule.put(PLAY_MODEL_LIST_LOOP, PLAY_MODEL_RANDOM);
        sPlayModeRule.put(PLAY_MODEL_RANDOM, PLAY_MODEL_SINGLE_LOOP);
        sPlayModeRule.put(PLAY_MODEL_SINGLE_LOOP, PLAY_MODEL_LIST_LOOP);
    }

    private ViewPopWindow mViewPopWindow;
    private ValueAnimator mEnterBgAnimator;
    private ValueAnimator mOutBgAnimator;
    public final int BG_ANIMATION_DURATION = 500;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_player);
        initView();
        mInstanceImplPlayerLogic = ImplPlayerLogic.getInstanceImplPlayerLogic();
        mPlayerViewCallback = new PlayerViewCallback();
        mInstanceImplPlayerLogic.registerViewCallback(mPlayerViewCallback);
        initEvent();
        initBgAnimation();
    }

    private void initView() {
        initNavBar(true,"播放器");
        mPlayOrPauseBtn = findViewById(R.id.play_or_pause);
        mDurationTime = findViewById(R.id.track_duration);
        mCurrPosTime = findViewById(R.id.current_position);
        mDurationSeekBar = findViewById(R.id.track_seek_bar);
        mPlayPreBtn = findViewById(R.id.play_pre);
        mPlayNextBtn = findViewById(R.id.play_next);
        mTrackTitle = findViewById(R.id.track_title);
        if (!TextUtils.isEmpty(mTrackTitleText)) {
            mTrackTitle.setText(mTrackTitleText);
        }
        mTrackViewPager = findViewById(R.id.track_view_pager);
        mAdapterPlayerTrackViewPager = new AdapterPlayerTrackViewPager();
        mTrackViewPager.setAdapter(mAdapterPlayerTrackViewPager);
        mPlayModeSwitchBtn = findViewById(R.id.player_mode_switch_btn);
        mPlayerListBtn = findViewById(R.id.player_list);
        mViewPopWindow = new ViewPopWindow();
    }

    @SuppressLint("ClickableViewAccessibility")
    private void initEvent() {
        mPlayOrPauseBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mInstanceImplPlayerLogic != null) {
                    //如果现在的状态是正在播放的,那么就暂停
                    if (mInstanceImplPlayerLogic.isPlaying()) {
                        mInstanceImplPlayerLogic.pause();
                    } else {
                        //如果现在的状态是非播放的,那么我们就让播放器播放节目
                        mInstanceImplPlayerLogic.play();
                    }
                }
            }
        });

        mDurationSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    mCurrentPragress = progress;
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                mIsUserTouchProgressBar = true;
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                mIsUserTouchProgressBar = false;
                if (mInstanceImplPlayerLogic != null) {
                    //手离开拖动进度条的时候更新进度
                    mInstanceImplPlayerLogic.seekTo(mCurrentPragress);
                }
            }
        });

        mPlayPreBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //播放上一曲
                if (mInstanceImplPlayerLogic != null) {
                    mInstanceImplPlayerLogic.playPre();
                }
            }
        });

        mPlayNextBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //播放下一曲
                if (mInstanceImplPlayerLogic != null) {
                    mInstanceImplPlayerLogic.playNext();
                }
            }
        });

        mTrackViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            //在页面上滚动
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            //在所选页面上，就去切换播放的内容
            public void onPageSelected(int position) {
                UtilLog.d(TAG,"position ==> "+position);
                if (mInstanceImplPlayerLogic != null&&mIsUserSlidePager) {
                    mInstanceImplPlayerLogic.playByIndex(position);
                }
                mIsUserSlidePager = false;
            }

            @Override
            //页面滚动状态已更改
            public void onPageScrollStateChanged(int state) {

            }
        });

        mTrackViewPager.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int action = event.getAction();
                switch (action) {
                   case MotionEvent.ACTION_DOWN:
                       mIsUserSlidePager = true;
                    break;
                }
                return false;
            }
        });

        mPlayModeSwitchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switchPlayMode();
            }
        });

        mPlayerListBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //展示播放列表
                mViewPopWindow.showAtLocation(v, Gravity.BOTTOM,0,0);//在位置显示
                //设置背景透明的渐变过程
                mEnterBgAnimator.start();
            }
        });

        //设置点击消失的监听器
        mViewPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                //pop窗体消失以后，恢复透明度
               mOutBgAnimator.start();
            }
        });

        mViewPopWindow.setOnPlayListItemClickListener(new ViewPopWindow.OnPlayListItemClickListener() {
            @Override
            public void onItemClick(int postion) {
                //播放列表的Item被点击了
                if (mInstanceImplPlayerLogic != null) {
                    mInstanceImplPlayerLogic.playByIndex(postion);
                }
            }
        });
        mViewPopWindow.setOnPlayListActionClickListener(new ViewPopWindow.OnPlayListActionClickListener() {
            @Override
            public void onPlayListModeSwitchClick() {
                //切换播放模式
                switchPlayMode();
            }

            @Override
            public void onPlayListOrderClick() {
                if (mInstanceImplPlayerLogic != null) {
                    mInstanceImplPlayerLogic.reversePlayList();
                }
            }
        });
   }


    private void switchPlayMode() {
        //根据当前的mode获取到下一个mode
        XmPlayListControl.PlayMode playMode = sPlayModeRule.get(mCurrentMode);
        //修改播放模式
        if (mInstanceImplPlayerLogic != null) {
            mInstanceImplPlayerLogic.switchPlayMode(playMode);
        }
    }

    public void updateBgAlpha(float alpha){
       Window window = getWindow();
       WindowManager.LayoutParams attributes = window.getAttributes();
       attributes.alpha = alpha;
       window.setAttributes(attributes);
   }

    private void initBgAnimation() {
        //进入的
        mEnterBgAnimator = ValueAnimator.ofFloat(1.0f, 0.7f);
        mEnterBgAnimator.setDuration(BG_ANIMATION_DURATION);
        mEnterBgAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            //动画更新监听器
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (float) animation.getAnimatedValue();
                //处理背景，设置透明度
                updateBgAlpha(value);
            }
        });
        //退出的
        mOutBgAnimator = ValueAnimator.ofFloat(0.7f, 1.0f);
        mOutBgAnimator.setDuration(BG_ANIMATION_DURATION);
        mOutBgAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (float) animation.getAnimatedValue();
                updateBgAlpha(value);
            }
        });
    }






    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mInstanceImplPlayerLogic != null) {
            mInstanceImplPlayerLogic.unRegisterViewCallback(mPlayerViewCallback);
            mInstanceImplPlayerLogic = null;
        }
    }










    /**
     * 播放器界面UI视图回调的内部类
     */
    private class PlayerViewCallback implements IPlayerViewCallback{
        @Override
        public void onPlayStart() {
            //修改UI成暂停的按钮
            if (mPlayOrPauseBtn != null) {
                mPlayOrPauseBtn.setImageResource(R.drawable.selector_player_stop);
            }
        }

        @Override
        public void onPlayPause() {
            //修改UI成播放的按钮
            if (mPlayOrPauseBtn != null) {
                mPlayOrPauseBtn.setImageResource(R.drawable.selector_player_play);
            }
        }

        @Override
        public void onPlayStop() {
            //修改UI成播放的按钮
            if (mPlayOrPauseBtn != null) {
                mPlayOrPauseBtn.setImageResource(R.drawable.selector_player_play);
            }
        }

        @Override
        public void onPlayError() {

        }

        @Override
        public void onPrePlay(Track track) {

        }

        @Override
        public void nextPlay(Track track) {

        }


        @Override
        public void onPlayModeChange(XmPlayListControl.PlayMode playMode) {
            mCurrentMode=playMode;

            //更新popView里的的播放模式
            mViewPopWindow.updatePlayListModeUI(playMode);
            //更新播放器内的播放模式
            int resId = R.drawable.selector_play_mode_list_loop;
            switch (mCurrentMode) {
                case PLAY_MODEL_LIST_LOOP:
                    resId = R.drawable.selector_play_mode_list_loop;
                    break;
                case PLAY_MODEL_RANDOM:
                    resId = R.drawable.selector_play_mode_random;
                    break;
                case PLAY_MODEL_SINGLE_LOOP:
                    resId = R.drawable.selector_play_mode_single_loop;
                    break;
            }
            mPlayModeSwitchBtn.setImageResource(resId);

        }

        @Override
        public void onListLoaded(List<Track> list) {
            if (mAdapterPlayerTrackViewPager != null) {
                //把数据设置到适配器里
                mAdapterPlayerTrackViewPager.setData(list);
            }
            //数据回来以后，也要给节目列表一份
            if (mViewPopWindow != null) {
                mViewPopWindow.setPlayListData(list);
            }
        }

        @Override
        public void onProgressChange(int currPos, int duration) {
            mDurationSeekBar.setMax(duration);
            //更新当前进度时间，更新总共时长
            String currPosTime;//当前进度
            String durationTime;//总共时长
            if (duration>1000*60*60) {
                currPosTime = mHourFormat.format(currPos);
                durationTime= mHourFormat.format(duration);
            }else {
                currPosTime = mMinFormat.format(currPos);
                durationTime = mMinFormat.format(duration);
            }
            if (mCurrPosTime != null) {
                mCurrPosTime.setText(currPosTime);
            }
            if (mDurationTime != null) {
                mDurationTime.setText(durationTime);
            }

            //更新进度条的进度
            if (!mIsUserTouchProgressBar) {
                if (mDurationSeekBar != null) {
                    mDurationSeekBar.setProgress( currPos);
                }
            }
        }


        @Override
        public void onAdLoading() {

        }

        @Override
        public void onAdFinished() {

        }

        @Override
        public void onTrackUpdate(Track track, int playIndex) {
            if (track==null) {
                UtilLog.d(TAG,"onTrackUpdate ==> track null.");
                return;
            }
            mTrackTitleText = track.getTrackTitle();
            //设置当前节目的标题
            if (mTrackTitle != null) {
                mTrackTitle.setText(track.getTrackTitle());
            }
            //当节目改变的时候，就获取当前播放中的位置
            //当前的节目改变以后，要修改页面的图片
            if (mTrackViewPager != null) {
                mTrackViewPager.setCurrentItem(playIndex,true);//true,有切换动画.false,无切换动画
            }

            //修改播放列表里的播放位置
            if (mViewPopWindow != null) {
                mViewPopWindow.setCurrentPlayPosition(playIndex);
            }
        }

        @Override
        public void updateListOrder(boolean isReverse) {
            mViewPopWindow.updatePlayListOrderUI(isReverse);
        }
    }
}
